package com.cdg.polymeric.autoconfigure;

import com.cdg.polymeric.BeanFactoryUtils;
import com.cdg.polymeric.core.ext.mybatis.PolymericMybatisPlugin;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Properties;

@Configuration
@ConditionalOnBean(SqlSessionFactory.class)
@EnableConfigurationProperties(PolymericProperties.class)
@AutoConfigureAfter(MybatisAutoConfiguration.class)
@Lazy(false)
public class PolymericAutoConfiguration {

    @Autowired
    private List<SqlSessionFactory> sqlSessionFactoryList;
    @Autowired
    PolymericProperties polymericProperties;


      @Bean
      @ConditionalOnMissingBean
      public BeanFactoryUtils beanFactoryUtils() {
          return new BeanFactoryUtils();
      }


    public Properties polymericProperties() {
        Properties properties = new Properties();
        properties.put("guavaCacheNumMaxSize",polymericProperties.getGuavaCacheNumMaxSize());
        properties.put("guavaCacheRefreshWriteTime",polymericProperties.getGuavaCacheRefreshWriteTime());
        properties.put("guavaCacheRefreshThreadPoolSize",polymericProperties.getGuavaCacheRefreshThreadPoolSize());
        return properties;
    }


    private boolean containsInterceptor(org.apache.ibatis.session.Configuration configuration, Interceptor interceptor) {
        try {
            return configuration.getInterceptors().contains(interceptor);
        } catch (Exception var4) {
            return false;
        }
    }

    @PostConstruct
    public void addInterceptor() throws Exception {
        PolymericMybatisPlugin interceptor = new PolymericMybatisPlugin();
        Properties properties = new Properties();

        properties.putAll(polymericProperties());
        interceptor.setProperties(properties);
        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList){

            org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration();
            if (!this.containsInterceptor(configuration, interceptor)) {
                configuration.addInterceptor(interceptor);
            }
        }
    }
}
